package com.hd.trans.files.aty;

import android.os.Bundle;
import android.util.Pair;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.hd.trans.R;
import com.hd.trans.db.bean.TransitionType;
import com.hd.trans.files.FileSortDialogFragment;
import com.hd.trans.files.adapter.CommonViewPagerAdapter;
import com.hd.trans.files.bean.Audio;
import com.hd.trans.files.fragment.MediaListFragment;
import com.hd.trans.files.model.NextButtonUiModel;
import com.hd.trans.files.model.PickingFileViewModel;
import com.hd.trans.files.model.TabViewUiModel;
import com.hd.trans.ui.base.BaseActivity;
import com.hd.trans.utils.Constant;
import com.hd.trans.utils.DisplayUtils;
import com.hd.trans.utils.KeyEventUtil;
import com.hd.trans.widgets.CommonSearchView;

import java.util.ArrayList;
import java.util.List;

/**
 * 选择文件页面
 */
public class PickingFileActivity extends BaseActivity {

    private TabLayout mTabLayout;
    private ViewPager2 mViewPager;
    private TextView mTextHint;

    private CommonViewPagerAdapter mViewPagerAdapter;

    private PickingFileViewModel mViewModel;
    private View sortImage;
    private View sortText;
    private KeyEventUtil keyEventUtil;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_picking_file;
    }


    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        initView();
        initViewModel();
    }

    @Override
    public void onBackPressed() {
//        if (mViewPager.getCurrentItem() == mViewPagerAdapter.getItemCount() - 1) {
//            mViewModel.onBackPressed(mTextHint.getText().toString());
//        } else {
//            super.onBackPressed();
//        }
        super.onBackPressed();
    }

    private void initViewModel() {
        ArrayList<Audio> selectedAudios = null;
        int translationType = TransitionType.DOCUMENT;
        if (getIntent() != null) {
//            selectedAudios = getIntent().getParcelableArrayListExtra(EXTRA_AUDIO_LIST);
            translationType = getIntent().getIntExtra(Constant.EXTRA_TRANSLATION_TYPE, TransitionType.DOCUMENT);
        }
        mViewModel = new ViewModelProvider(this,
                new PickingFileViewModel.PickingViewModelFactory(getApplication(), selectedAudios, translationType))
                .get(PickingFileViewModel.class);
        getLifecycle().addObserver(mViewModel);

        mViewModel.getTabLayoutObserver().observe(this, this::setupTabLayout);

        // 根据选择的文件数量更新 下一步 按钮状态
        mViewModel.getEnableNextObserver().observe(this, this::updateNextButton);

        // 在从文件路径选择文件时，更新当前路径
//        mViewModel.getCurrentPathObserver().observe(this, this::updateCurrentPath);

        mViewModel.getFinishActivityObserver().observe(this, finish -> {
            if (finish) finish();
        });

        // 显示进度条弹窗
        mViewModel.getProgressUiViewModel().getProgressStartObserver()
                .observe(this, this::onProgressStart);

        // 更新进度条弹窗
        mViewModel.getProgressUiViewModel().getProgressingObserver()
                .observe(this, this::onProgressUpdating);

        // 进度条结束
        mViewModel.getProgressUiViewModel().getProgressEndObserver()
                .observe(this, this::onProgressEnd);

        // 显示Toast
        mViewModel.getToastObserver().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {

            }
        });
    }

    /**
     * 进度条结束
     */
    private void onProgressEnd(boolean success) {
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    /**
     * 更新进度条弹窗
     */
    private void onProgressUpdating(Pair<Integer, Integer> progress) {
    }

    /**
     * 进度条弹窗提醒处理
     */
    private void updateProgressHint(Pair<Integer, Integer> progress, int size, @StringRes int resId) {
        int index = progress.first / progress.second + 1;
        if (index >= size) index = size;
    }

    /**
     * 进度条显示
     */
    private void onProgressStart(int maxProgress) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }


    private void updateCurrentPath(String path) {
        if (mViewPager.getCurrentItem() == mViewPagerAdapter.getItemCount() - 1) {
//            mTextHint.setText(getString(R.string.search_hint_text, path));
        }
    }


    private View.OnClickListener sortClick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showSortDialog();
        }
    };

    private void initView() {
        CommonSearchView searchView = findViewById(R.id.picking_file_search_view);
        mTabLayout = findViewById(R.id.picking_file_tab_layout);
//        mTabLayout.setTabTextColors(R.color.primary_text_black, R.color.primary_color);
        findViewById(R.id.icon_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        sortImage = findViewById(R.id.sort_image);
        sortText = findViewById(R.id.sort_text);
        sortImage.setOnClickListener(sortClick);
        sortText.setOnClickListener(sortClick);
        mViewPager = findViewById(R.id.picking_file_vp);
        mTextHint = findViewById(R.id.picking_file_tv_hint);
        mTextHint.setVisibility(View.GONE);

        //监听软键盘状态。
        if (keyEventUtil == null) {
            keyEventUtil = new KeyEventUtil(this);
        }
        keyEventUtil.setListener(new KeyEventUtil.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                // 隐藏tabLayout
                mTabLayout.setVisibility(View.GONE);
//                new ViewGroup.LayoutParams();
//                mTabLayout.setLayoutParams();
//                mTabLayout.startAnimation(R.anim.bottom_in);
            }

            @Override
            public void keyBoardHide(int height) {
                //  显示tabLayout
                mTabLayout.setVisibility(View.VISIBLE);
            }
        });
//        setSingleClickListener(mNextButton, v -> clickNext());

        // 监听 SearchView 的内容进行搜索
        searchView.getTextChangeObserver().observe(
                this,
                text -> mViewModel.doSearchAudioWithKeyWord(text)
        );
    }

    private void showSortDialog() {
        FileSortDialogFragment sortDialogFragment = FileSortDialogFragment.newInstance();
        sortDialogFragment.show(getSupportFragmentManager(), "");
        sortDialogFragment.setFileSortListener(mViewModel.getFilesSortObserver().getValue(),
                modeItem -> mViewModel.getFilesSortObserver().setValue(modeItem.getMethod())
        );
    }

    private void setupViewPager(List<TabViewUiModel> tabs) {
        mViewPagerAdapter = new CommonViewPagerAdapter(this);
        List<Fragment> fragments = new ArrayList<>();
        for (TabViewUiModel tab : tabs) {
            fragments.add(tab.getFragment());
        }
        mViewPager.setAdapter(mViewPagerAdapter);
        mViewPager.setOffscreenPageLimit(fragments.size());
        mViewPagerAdapter.setFragments(fragments);
        mViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                if (position == mViewPagerAdapter.getItemCount() - 1) {
                    showCurrentPath();
                } else {
                    showHintTextView();
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
            }
        });
    }

    private void setupTabLayout(List<TabViewUiModel> tabs) {
        setupViewPager(tabs);
        new TabLayoutMediator(mTabLayout, mViewPager, (tab, position) -> {
            tab.setCustomView(R.layout.layout_tab_item);
            tab.setText(tabs.get(position).getTitle() + "(" + "0)");
            tab.setIcon(tabs.get(position).getIcon());
            Fragment fragment = tabs.get(position).getFragment();
            if (fragment instanceof MediaListFragment) {
                ((MediaListFragment) fragment).setTab(tab, tabs.get(position).getTitle());
            }
        }).attach();
    }

    /**
     * 更新下一步按钮状态
     */
    private void updateNextButton(NextButtonUiModel nextButton) {
//        mNextButton.setText(getString(R.string.text_translate, nextButton.getSelectedCount()));
    }

    /**
     * 显示当前文件路径
     */
    private void showCurrentPath() {
        int paddingHorizontal = DisplayUtils.dp2px(this, 26f);
        int paddingVertical = DisplayUtils.dp2px(this, 5f);
        mTextHint.setPadding(paddingHorizontal, paddingVertical, paddingHorizontal, paddingVertical);
        mTextHint.setGravity(Gravity.START);
        mViewModel.showCurrentPath();
    }

    /**
     * 显示提示信息
     */
    private void showHintTextView() {
        int paddingHorizontal = DisplayUtils.dp2px(this, 40f);
        int paddingVertical = DisplayUtils.dp2px(this, 5f);
        mTextHint.setPadding(paddingHorizontal, paddingVertical, paddingHorizontal, paddingVertical);
        mTextHint.setGravity(Gravity.CENTER);
//        mTextHint.setText(getString(R.string.picking_file_hint));
    }

    private void clickNext() {
    }


    @Override
    protected void onPause() {
        super.onPause();
    }

}